package cn.itcast.mongodb;

import java.net.UnknownHostException;

import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

/**
 * 
 * 使用java 代码来调用mongodb 
 * @author Administrator
 *
 */
public class MongoDBDao {
	
	private Mongo mongo = null;
	private DBCollection dbCollection = null;
	
	
	@Before
	public void init() throws UnknownHostException{
		mongo=new Mongo("localhost", 27017);
		DB db=mongo.getDB("test");
		dbCollection=db.getCollection("c1");
	}
	
	@Test
	public void testAdd(){
		
		
		BasicDBObject dbObject=new BasicDBObject();
		
		dbObject.put("name", "李东浩");
		
		dbObject.put("age", 3306);
		
		dbCollection.insert(dbObject);
		
		mongo.close();
	}

	@Test
	public void testfind() {
		DBCursor cursor=dbCollection.find();
		while(cursor.hasNext()){
			DBObject dbObject=cursor.next();
			System.out.println(dbObject.toString());
			System.out.println(dbObject.get("name"));
		}
		mongo.close();
	}
	
	@Test
	public void testUpdate() {
		DBObject dbq = new BasicDBObject();//条件
		DBObject dbo = new BasicDBObject();//修改值
		dbq.put("name", "zhangsan");
		dbo.put("age",44);
		dbCollection.update(dbq, dbo);
		mongo.close();
	}
	
	@Test
	public void testDelete() {
		DBObject dbo = new BasicDBObject();
		dbo.put("name", "李东浩");
		dbCollection.remove(dbo);
		mongo.close();
	}
	//写个爬虫把网易新闻的新闻频道数据还有搜狐新闻频道，sina 新闻抓取下来，使用lucene 建立索引，在通过全文检索查找...
}
